package com.fc.remoting.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fc.remoting.RemotingConst;
import com.fc.remoting.logger.RemotingLogger;
import com.fc.remoting.message.Commond;
import com.fc.remoting.protocol.ProtocolRegister;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;

public class HttpServiceHandler extends ChannelHandlerAdapter {
	private static Logger log = LoggerFactory.getLogger(HttpServiceHandler.class);

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg instanceof HttpRequest) {
			HttpRequest request = (HttpRequest) msg;
			System.out.println("Uri:" + request.getUri());
		}
		if (msg instanceof HttpContent) {
			HttpContent content = (HttpContent) msg;
			ByteBuf buf = content.content();
			String msgContent = buf.toString(io.netty.util.CharsetUtil.UTF_8);

			RemotingLogger.getLogger()
					.info("body length:" + content.content().capacity() + "\n" + "body:" + msgContent);

			JSONObject jObject = JSONObject.parseObject(msgContent);
			int module = jObject.getIntValue(RemotingConst.MODULE);
			int order = jObject.getIntValue(RemotingConst.ORDER);
			Commond commond = Commond.valueOf(module, order);
			com.fc.remoting.protocol.ProtocolAdapter protocolAdapter = ProtocolRegister.getAdapter(commond);
			protocolAdapter.process(jObject, ctx);
			buf.release();
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		log.error(cause.getMessage());
		ctx.close();
	}
}
